import { getPersonStudyDetailList, PlanPersonListItem } from '@/api/StatisticsApi';
import { useAppSelector } from '@/redux/store';
import { FC, Ref, useEffect, useImperativeHandle, useMemo, useState } from 'react';
import { YmDialog, YmTable, type YmColumnsType } from 'ym-design';

export type PersonStudyTableProps = {
  finishState?: number | string;
  planCourseId?: string;
  cycleId?: string;
  title?: string;
  //des 是否隐藏查询条件
  isHiddenSearch?: boolean;
  entId: string;
  from?: string;
  enterpriseId?: string;
};

interface Props {
  props: PersonStudyTableProps;
  innerRef: Ref<{ showModal: (params: any) => void } | undefined>;
  onChange: () => void;
}

export const PersonStudyDetailModal: FC<Props> = ({ props, innerRef, onChange }) => {
  const { entId } = props;
  // organizationType - 1: 协会; 0: 企业
  const { organizationType } = useAppSelector((state) => state.loginEnt);
  const [isOpen, setIsOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [refreshFlag, _setRefreshFlag] = useState(false);

  useEffect(() => {
    setConfirmLoading(false);
    _setRefreshFlag((v) => !v);
  }, [isOpen, props]);

  /**
   * 打开弹窗
   */
  const showModal = () => {
    setIsOpen(true);
  };

  useImperativeHandle(innerRef, () => ({ showModal: showModal }));

  const columns: YmColumnsType<PlanPersonListItem> = useMemo(
    () => [
      {
        title: '编号',
        dataIndex: 'No',
        key: 'No',
        width: 80,
        render(value) {
          return value < 10 ? '0' + value : value;
        },
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        width: 100,
        ellipsis: true,
      },
      {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone',
        width: 123,
        ellipsis: true,
      },
      {
        title: '入职企业',
        dataIndex: 'entName',
        key: 'entName',
        width: 180,
        ellipsis: true,
        hidden: organizationType === 0,
        render(value, record) {
          if (record.joinList && record.joinList.length) {
            const enterpriseNames = record.joinList.map((item) => item.name);
            const displayName = enterpriseNames[0];

            if (enterpriseNames.length > 1) {
              return (
                <div>
                  {displayName}等{enterpriseNames.length}家企业
                </div>
              );
            } else {
              return <div>{displayName}</div>;
            }
          } else {
            return <div style={{ color: '#f66e2c' }}>暂无入职企业</div>;
          }
        },
      },
      {
        title: '人员类型',
        dataIndex: 'positionNameByAssociation',
        key: 'positionNameByAssociation',
        width: 120,
        ellipsis: true,
        hidden: organizationType === 0,
        // render(value, record) {
        //   const extraInfo = record?.extraInfo?.find((item) => item.title === '人员职位');

        //   return (
        //     <>
        //       <span>{extraInfo?.value ?? '--'}</span>
        //     </>
        //   );
        // },
      },
      {
        title: '学习状态',
        dataIndex: 'finishStatus',
        key: 'finishStatus',
        width: 100,
        render(value) {
          return value === 1 ? (
            <span style={{ color: '#3BD59A' }}>已学习</span>
          ) : (
            <span style={{ color: '#FF4A4A' }}>未学习</span>
          );
        },
      },
      {
        title: '完成学习时间',
        dataIndex: 'finishTime',
        key: 'finishTime',
        width: 120,
      },
    ],
    [],
  );

  return (
    <YmDialog
      title={props.title ? props.title : '人员学习明细'}
      styles={{
        footer: {
          display: 'none',
        },
      }}
      open={isOpen}
      onClose={() => setIsOpen(false)}
      width={1120}
      centered
      destroyOnClose
    >
      <YmTable
        wrapperStyle={{
          height: 400,
          padding: 0,
        }}
        columns={columns}
        toolBar={false}
        searchForm={{
          span: 6,
          formItems: !props.isHiddenSearch
            ? [
                {
                  name: 'personName',
                  label: '姓名',
                  valueType: {
                    inputProps: {
                      type: 'input',
                    },
                  },
                },
                {
                  name: 'phone',
                  label: '电话',
                  valueType: {
                    inputProps: {
                      type: 'input',
                    },
                  },
                },
                {
                  name: 'finishState',
                  label: '学习状态',
                  valueType: {
                    type: 'select',
                    selectProps: {
                      defaultValue: props.finishState,
                      getPopupContainer: (trigger) => trigger,
                      options: [
                        { label: '全部', value: '' },
                        { label: '已学习', value: 1 },
                        { label: '未学习', value: 2 },
                      ],
                      showSearch: false,
                      maxTagCount: 1,
                    },
                  },
                },
              ]
            : (undefined as any),
        }}
        request={async ({ page }, value = {}) => {
          let url, params;

          const state = value.finishState === undefined ? props.finishState : value.finishState;

          if (organizationType === 1) {
            // 协会
            if (props.from == 'detail') {
              // NOTE: 这个暂时不要用
              url = '/safe/api/statistics/planStudyPersonSituationList';
            } else {
              params = {
                ...props,
                ...value,
                finishState: state,
                entId,
              };
              url = '/safe/api/statistics/assStudyPersonList';
            }
          } else {
            // 企业
            const { planCourseId, cycleId, entId, enterpriseId } = props;

            params = {
              cycleId,
              planCourseId,
              ...value,
              finishState: state,
              entId: enterpriseId,
              curEntId: entId,
            };

            url = '/safe/api/statistics/entStudyPersonList';
          }

          const result = await getPersonStudyDetailList(url, params, page?.pageIndex, page?.pageSize);

          return result;
        }}
        requestOptions={{
          reFreshDep: [refreshFlag],
        }}
      />
    </YmDialog>
  );
};
